#include "KVCommand.h"

#include "raft_utils/DataStream.h"

std::string KVCommand::as_string() const {
    std::string command = command_to_string();
    raft::utils::DataStream data_stream;
    data_stream << command << key_ << value_;
    std::string serialized_str(data_stream.data(), data_stream.size());
    return serialized_str;
}

bool KVCommand::parse_from_string(const std::string &str) {
    if (str.empty()) {
        return false;
    }
    raft::utils::DataStream data_stream;
    std::vector<char> dump_buffer(str.c_str(), str.c_str() + str.size());
    data_stream.write(dump_buffer.data(), dump_buffer.size());
    std::string command;
    data_stream >> command >> key_ >> value_;
    string_to_command(command);
    return true;
}

void KVCommand::clear() {
    command_ = Command::None;
    key_.clear();
    value_.clear();
}


std::string KVCommand::command_to_string() const {
    switch (command_) {
        case Command::INSERT:
            return "INSERT";
        case Command::SET:
            return "SET";
        case Command::DELETE:
            return "DELETE";
        case Command::SEARCH:
            return "SEARCH";
        default:
            return "None";
    }
}

void KVCommand::string_to_command(const std::string &str) {
    if (str == "INSERT") {
        command_ = Command::INSERT;
    } else if (str == "SET") {
        command_ = Command::SET;
    } else if (str == "DELETE") {
        command_ = Command::DELETE;
    } else if (str == "SEARCH") {
        command_ = Command::SEARCH;
    } else {
        command_ = Command::None;
    }
}

KVCommand::Command KVCommand::get_command() const {
    return command_;
}

void KVCommand::set_command(KVCommand::Command command) {
    command_ = command;
}

const std::string &KVCommand::get_key() const {
    return key_;
}

void KVCommand::set_key(const std::string &key) {
    key_ = key;
}

const std::string &KVCommand::get_value() const {
    return value_;
}

void KVCommand::set_value(const std::string &value) {
    value_ = value;
}